package com.ruoyi.attendance.service.impl;

import com.ruoyi.attendance.domain.Attendance;
import com.ruoyi.attendance.domain.AttendanceVO;
import com.ruoyi.attendance.mapper.AttendanceMapper;
import com.ruoyi.attendance.service.AttendanceService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AttendanceServiceImpl implements AttendanceService {

    @Autowired
    private AttendanceMapper attendanceMapper;

    @Override
    public List<Attendance> selectAttendanceList(Attendance attendance)
    {


        Long userId = SecurityUtils.getUserId();
        String roleType = getRoleTypeByUserId(userId);
        System.out.println(roleType);
        if ( "1".equals(roleType)){
            return attendanceMapper.selectAttendanceList(attendance);
        } else {
            return attendanceMapper.selectAttendanceListByUserId(userId);
        }
    }

    @Override
    public String selectAttendanceById(Long id) {
        return null;
    }


    @Override
    public void insertAttendance()
    {
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();

        Attendance attendance = new Attendance();
        attendance.setUserId(userId);
        attendance.setUsername(username);

        // 获取当前日期和时间
        Date now = DateUtils.getNowDate();
        Date today = new Date(now.getYear(), now.getMonth(), now.getDate()); // 只获取日期部分，忽略时间

        // 查询用户当天的考勤记录
        Attendance existingAttendance = attendanceMapper.selectAttendanceByUserIdAndDate(
                attendance.getUserId(),
                today
        );

        if (existingAttendance != null) {
            // 创建新的考勤记录对象，不修改原有记录
            Attendance newAttendance = new Attendance();
            newAttendance.setUserId(existingAttendance.getUserId());
            newAttendance.setUsername(existingAttendance.getUsername());
            newAttendance.setCheckInTime(existingAttendance.getCheckInTime());
            newAttendance.setCheckOutTime(now);

            // 判断是否早退（下班时间早于18点）
            boolean isEarlyLeave = newAttendance.getCheckOutTime() != null && newAttendance.getCheckOutTime().getHours() < 18;

            // 判断是否迟到（上班时间晚于9点）
            boolean isLateArrival = existingAttendance.getCheckInTime() != null && existingAttendance.getCheckInTime().getHours() > 9;

            // 设置状态
            if ("3".equals(existingAttendance.getStatus())) {
                // 如果已经是迟到早退状态，则保持原状态不变
                newAttendance.setStatus("3");
            } else if (isLateArrival && isEarlyLeave) {
                newAttendance.setStatus("3"); // 既迟到又早退
            } else if (isEarlyLeave) {
                newAttendance.setStatus("2"); // 早退
            } else if (isLateArrival) {
                newAttendance.setStatus("1"); // 迟到
            } else {
                newAttendance.setStatus("0"); // 正常
            }


            // 插入新的考勤记录
            attendanceMapper.insertAttendance(newAttendance);

            // 更新原有记录的check_out_time字段
            existingAttendance.setCheckOutTime(now);
            attendanceMapper.updateAttendance(existingAttendance);
        } else {
            // 没有考勤记录，处理上班打卡
            attendance.setCheckInTime(now);

            // 判断是否迟到（上班时间晚于9点）
            if (attendance.getCheckInTime() != null && attendance.getCheckInTime().getHours() > 9) {
                attendance.setStatus("1"); // 迟到
            } else {
                attendance.setStatus("0"); // 正常
            }

            attendanceMapper.insertAttendance(attendance);
        }
    }

    /**
     * 修改考勤记录
     *
     * @param attendance 考勤记录
     * @return 结果
     */
    @Override
    public int updateAttendance(Attendance attendance)
    {
        return attendanceMapper.updateAttendance(attendance);
    }
    @Override
    public int deleteAttendanceByIds(Long[] ids)
    {
        return attendanceMapper.deleteAttendanceByIds(ids);
    }

    @Override
    public AttendanceVO getAttendanceStats(Long userId) {
        return attendanceMapper.getAttendanceStats(userId);
    }


    public String getRoleTypeByUserId(Long userId) {
        return attendanceMapper.getRoleTypeByUserId(userId);

    }

}

